import {
  Table,
  Image,
  Switch,
  message,
} from 'antd'
import { useCallback, useMemo, useState } from 'react'
import { delFodderItemApi, postFodderItemFlagApi } from '../../../../api/fodder'
import DeleteButton from '../../../../components/DeleteButton'

const FodderTable = (props) => {
  const { data, refersh } = props
  const [pageInfo, setPageInfo] = useState({ page: 1, pageSize: 5 })
  const handleUpdataFlag = useCallback(async (bannerid, flag) => {
    try {
      await postFodderItemFlagApi({ bannerid, flag })
      refersh()
    } catch (error) {
      console.log(error)
    }
  }, [])
  const handleDelItem = useCallback(async (bannerid) => {
    try {
      await delFodderItemApi({ bannerid })
      refersh()
      message.success('恭喜您删除成功')
    } catch (error) {
      console.log(error)
    }
  }, [])
  const handlePageChange = useCallback((page, pageSize) => {
    setPageInfo({ page, pageSize })
  }, [])
  const columns = useMemo(() => [
    {
      key: 'index',
      title: '序号',
      render: (_, record, index) => (index + 1) + (pageInfo.page - 1) * pageInfo.pageSize,
    },
    {
      key: 'img',
      dataIndex: 'img',
      title: '图片',
      render: (_) => <Image src={_} style={{ width: '150px' }} />,
    },
    {
      key: 'alt',
      dataIndex: 'alt',
      title: 'Alt',
      render: (_) => (_),
    },
    {
      key: 'link',
      dataIndex: 'link',
      title: 'Link',
      render: (_) => (<a>{_}</a>),
    },
    {
      key: 'state',
      dataIndex: 'flag',
      title: '访问状态',
      render: (flag, record) => <Switch checked={flag} onChange={() => handleUpdataFlag(record.bannerid, !flag)} />,
    },
    {
      key: 'operation',
      dataIndex: 'bannerid',
      title: '操作',
      render: (_) => <DeleteButton confirm={() => handleDelItem(_)} />,
    },
  ], [pageInfo])
  return (
    <Table rowKey="bannerid" pagination={{ pageSize: pageInfo.pageSize, showTotal: (total, range) => `当前页 ${range[0]}-${range[1]} 条, 共 ${total} 条数据`, onChange: handlePageChange }} dataSource={data} columns={columns} />
  )
}

export default FodderTable
